package cn.com.chengmandian.bike.controller;

import cn.com.chengmandian.agent.utils.AuthUtil;
import cn.com.chengmandian.agent.utils.ServletUtil;
import cn.com.chengmandian.bike.dto.*;
import cn.com.chengmandian.bike.log.ActionLog;
import cn.com.chengmandian.bike.model.*;
import cn.com.chengmandian.bike.model.vo.*;
import cn.com.chengmandian.bike.service.*;
import cn.com.chengmandian.bike.utils.AliPayUtil;
import cn.com.chengmandian.bike.utils.WxPayUtil;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.db.pojo.PageData;
import cn.com.chengmandian.core.redis.cache.AgentParamCacheService;
import cn.com.chengmandian.core.web.exceptions.BadResponseException;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.pojo.BikeAreaParam;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.com.chengmandian.service.bike.BikeBillClient;
import cn.com.chengmandian.service.bike.BikePayClient;
import cn.com.chengmandian.service.bike.constants.*;
import cn.com.chengmandian.service.bike.form.BikePayForm;
import cn.com.chengmandian.service.bike.form.UpdateBikeDispatchBillForm;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import cn.com.chengmandian.service.bike.pojo.DevicePath;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 电单车运营-骑行订单 前端控制器
 * </p>
 *
 * @author AutoGenerator
 * @since 2021-12-10
 */
@Api(tags = "骑行订单相关接口")
@RestController
@Slf4j
@RequestMapping("/ride/order")
public class EbRideOrderController {
    @Autowired
    private IEbRideOrderService rideOrderService;

    @Autowired
    private IEbDevicePathService devicePathService;

    @Autowired
    private IEbDeviceBikeService deviceBikeService;

    @Autowired
    private IEbMemberWalletService memberWalletService;

    @Autowired
    private IEbMemberInfoService memberInfoService;

    @Autowired
    private IEbMemberPayService memberPayService;

    @Autowired
    private IEbScanRecordService scanRecordService;

    @Autowired
    private IEbWorkDispatchService workDispatchService;

    @Autowired
    private AgentParamCacheService agentParamCacheService;

    @Autowired
    private IEbMemberCouponService memberCouponService;

    @Autowired
    private BikeBillClient bikeBillClient;

    @Autowired
    private IEbWorkMoveService workMoveService;

    @Autowired
    private IEbCommonParamService paramService;

    @Autowired
    private IEbPreOrderService preOrderService;

    @Autowired
    private IEbRidePenaltyService ridePenaltyService;

    @Autowired
    private IEbAgentInfoService agentInfoService;

    @Autowired
    private IEbPayAccountService payAccountService;

    @Autowired
    private BikePayClient payClient;

    @ApiOperation("我的订单列表")
    @GetMapping("/pages")
    public AjaxResult<PageData<RideOrderVo>> pages(RideOrderDto rideOrderDto) {
        rideOrderDto.setMemberId(AuthUtil.getAgentUser().getId());
        if (StrUtil.isNotBlank(rideOrderDto.getOrderStatus())) {
            rideOrderDto.setOrderStatusList(Arrays.asList(rideOrderDto.getOrderStatus().split(",")).stream().map(i -> Integer.parseInt(i)).collect(Collectors.toList()));
        }
        return AjaxResult.success(PageData.build(rideOrderService.pages(rideOrderDto)));
    }

    @ApiOperation("查看订单详情")
    @GetMapping("/detail/{orderNo}")
    public AjaxResult<RideOrderVo> detail(@PathVariable("orderNo") String orderNo) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        return AjaxResult.success(rideOrderService.detail(orderNo, AuthUtil.getAgentUser().getId()));
    }

    @ApiOperation("订单路径点列表")
    @GetMapping("/paths/{orderNo}")
    @Deprecated
    public AjaxResult<List<DevicePath>> paths(@PathVariable("orderNo") String orderNo) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        return AjaxResult.success(devicePathService.getOrderPaths(orderNo, AuthUtil.getAgentUser().getId()));
    }

    @ApiOperation("订单路径点列表v2")
    @GetMapping("/path/list")
    public AjaxResult<List<DevicePath>> pathList(String orderNo) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        return AjaxResult.success(devicePathService.getOrderPaths(orderNo, AuthUtil.getAgentUser().getId()));
    }

    @ApiOperation("新建骑行订单")
    @PostMapping("/add/{bikeNo}")
    public AjaxResult<EbRideOrder> add(@PathVariable("bikeNo") String bikeNo, @RequestBody MemberLocationForm memberLocationForm) {
        Assert.isTrue(StrUtil.isNotBlank(bikeNo), "缺少车辆编号");
        EbDeviceBike ebDeviceBike = deviceBikeService.getByNo(bikeNo);
        AgentUser agentUser = AuthUtil.getAgentUser();
        // 更新车辆扫码信息
        deviceBikeService.updateScanInfo(ebDeviceBike, agentUser, memberLocationForm);
        EbRideOrder ebRideOrder = null;
        try {
            BikeAreaParam bikeAreaParam = agentParamCacheService.getParam(ebDeviceBike.getAgentId(), ebDeviceBike.getAreaId());
            if(bikeAreaParam != null && !bikeAreaParam.getUserRideShareEnable()){
               throw new BadResponseException(521, "未开启共享运营");
            }
            if(ObjectUtil.isNotNull(bikeAreaParam) && ObjectUtil.isNotNull(bikeAreaParam.getUserRideEnable()) && !bikeAreaParam.getUserRideEnable()){
              throw new BadResponseException(514,bikeAreaParam.getUserRideStopNote());
            }
            // 检查用户是否可以骑行
            memberInfoService.checkOpenBike(agentUser, ebDeviceBike.getAgentId(), ebDeviceBike.getAreaId());

            // 检查车辆是否可以骑行
            deviceBikeService.checkOpenBike(agentUser, ebDeviceBike, memberLocationForm.getLng(), memberLocationForm.getLat());

            // 生成订单
            ebRideOrder = rideOrderService.addOrder(ebDeviceBike, memberLocationForm, agentUser);
            // 生成扫码记录
            scanRecordService.generateRecord(200, ebRideOrder.getId(), agentUser, ebDeviceBike,memberLocationForm.getLng(),memberLocationForm.getLat());

        }catch (BadResponseException ex){
            // 生成扫码记录
            scanRecordService.generateRecord(ex.getCode(), null, agentUser, ebDeviceBike,memberLocationForm.getLng(),memberLocationForm.getLat());
            throw ex;
        }

        // 调度有效性
//        workDispatchService.addRideOrder(ebRideOrder);

        // 挪车有效性
        workMoveService.addRideOrder(ebRideOrder, LocalMapUtil.getAgentInfo().getId());

        try {
            // 调度工单有效性
            bikeBillClient.updateBikeDispatchBill(LocalMapUtil.getAgentInfo().getId(), new UpdateBikeDispatchBillForm()
                    .setBikeNo(ebRideOrder.getBikeNo())
                    .setRideOrderId(ebRideOrder.getId())
                    .setRideOrderNo(ebRideOrder.getOrderNo())
                    .setRideOrderTime(ebRideOrder.getCreateTime()));
        } catch (Exception e) {
            log.error("bikeBillClient.updateBikeDispatchBill error!", e);
        }
        return AjaxResult.success(ebRideOrder);
    }

    @ApiOperation("获取骑行中订单，提供计费数据")
    @GetMapping("/riding")
    public AjaxResult<RidingVo> riding() {
        AgentUser agentUser = AuthUtil.getAgentUser();
        return AjaxResult.success(rideOrderService.riding(agentUser.getId()));
    }

    @ApiOperation("用户开锁")
    @PostMapping("/lock/open/{orderNo}")
    @ActionLog(name="用户开锁",description = "'参数orderNo：' + #orderNo&'memberLocationForm：'+#memberLocationForm")
    public AjaxResult openLock(@PathVariable("orderNo") String orderNo, @RequestBody MemberLocationForm memberLocationForm) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.openLock(orderNo, agentUser.getId());
        return AjaxResult.success("开锁成功");
    }

    @ApiOperation("打开头盔锁")
    @PostMapping("/helmet/open/{orderNo}")
    @ActionLog(name="打开头盔锁",description = "'参数orderNo：' + #orderNo&'memberLocationForm：'+#memberLocationForm")
    public AjaxResult openHelmet(@PathVariable("orderNo") String orderNo, @RequestBody MemberLocationForm memberLocationForm) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.openHelmet(orderNo, agentUser.getId());
        return AjaxResult.success("开锁成功");
    }

    @ApiOperation("临时锁车")
    @PostMapping("/lock/stop/{orderNo}")
    @ActionLog(name="用户临时锁车",description = "'参数orderNo：' + #orderNo&'memberLocationForm：'+#memberLocationForm")
    public AjaxResult stopLock(@PathVariable("orderNo") String orderNo, @RequestBody MemberLocationForm memberLocationForm) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        Assert.notNull(memberLocationForm.getLng(), "缺少lng");
        Assert.notNull(memberLocationForm.getLat(), "缺少lat");
        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.memberStopLock(orderNo, agentUser.getId(), memberLocationForm.getSendStopCommand());
        return AjaxResult.success("停车成功");
    }

    @ApiOperation("响铃寻车")
    @PostMapping("/bell")
    public AjaxResult orderBell(@RequestBody RideOrderBellForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getOrderNo()), "缺少订单编号");

        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.memberOrderBell(form.getOrderNo(), agentUser.getId());
        return AjaxResult.success("响铃成功");
    }

    @ApiOperation("是否规范停车(废弃)")
    @PostMapping("/check/stop/{orderNo}")
    public AjaxResult checkStop(@PathVariable("orderNo") String orderNo){
        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.memberCheckStop(orderNo, null, agentUser.getId());
        return AjaxResult.success();
    }

    @ApiOperation("是否规范停车V2(废弃)")
    @PostMapping("/v2/check/stop")
    public AjaxResult checkStopV2(@RequestBody CheckStopForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getOrderNo()), "缺少订单号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.memberCheckStop(form.getOrderNo(), form.getAiPhotosPass(), agentUser.getId());
        return AjaxResult.success();
    }

    @ApiOperation("AI拍照规范停车")
    @PostMapping("/ai/photos/stop")
    public AjaxResult aiPhotosStop(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(value = "orderNo") String orderNo,
                                   @RequestParam(value = "isDispatch", required = false, defaultValue = "0") Integer isDispatch) {
        if(isDispatch == null || isDispatch.equals(CommonConstant.ZERO)) {
            Assert.isTrue(!file.isEmpty(), "未识别到图片");
        }
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        Integer memberId = AuthUtil.getAgentUser().getId();
        EbRideOrder rideOrder = rideOrderService.getByNo(orderNo, memberId);
        rideOrderService.memberAiPhotosStop(file, isDispatch, orderNo, memberId);
        BikeAreaParam bikeAreaParam = agentParamCacheService.getParam(rideOrder.getAgentId(), rideOrder.getAreaId());
        OrderCloseCheckVo vo = new OrderCloseCheckVo(bikeAreaParam == null? CommonConstant.ONE : bikeAreaParam.getUserRideReturnBikeProcess());
        return AjaxResult.success("停车成功", vo);
    }

    @ApiOperation("结束锁车")
    @PostMapping("/lock/close/{orderNo}")
    @ActionLog(name="结束锁车",description = "'参数orderNo：' + #orderNo&'memberLocationForm：'+#memberLocationForm")
    public AjaxResult closeLock(@PathVariable("orderNo") String orderNo, @RequestBody MemberLocationDisptachForm memberLocationForm) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        Assert.notNull(memberLocationForm.getLng(), "缺少lng");
        Assert.notNull(memberLocationForm.getLat(), "缺少lat");
        AgentUser agentUser = AuthUtil.getAgentUser();
        rideOrderService.memberCloseLock(orderNo, agentUser.getId(), memberLocationForm);
        return AjaxResult.success("锁车成功");
    }

    @ApiOperation("查询还车结果")
    @GetMapping("/close/result")
    public AjaxResult<GetCloseResultVo> getCloseResult(String orderNo) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        return AjaxResult.success(rideOrderService.getCloseResult(orderNo, agentUser.getId(), UserTypeEnum.MEMBER.getCode()));
    }

    @ApiOperation("订单评价")
    @PostMapping("/member/evaluate")
    public AjaxResult memberOrderEvaluate(@RequestBody RideOrderForm rideOrderForm){
        Assert.isTrue(rideOrderForm.getId() != null,"没有获取到数据信息!");
        rideOrderService.memberOrderEvaluateData(rideOrderForm);
        return AjaxResult.success();
    }

    @ApiOperation("获取一条未支付订单-不会报错，data可能为空")
    @GetMapping("/unpaid")
    public AjaxResult unpaid() {
        return AjaxResult.success(rideOrderService.getUserConfirmOrder(AuthUtil.getAgentUser().getId()));
    }

    @ApiOperation("待支付订单，自主选择使用优惠券")
    @PostMapping("/use/coupon")
    public AjaxResult useCoupon(@RequestBody RideOrderUseCouponForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getOrderNo()), "缺少订单号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        EbRideOrder rideOrder = rideOrderService.getByNo(form.getOrderNo(), agentUser.getId());
        Assert.notNull(rideOrder, "不存在的订单号");
        Assert.isTrue(rideOrder.getStatus().equals(RideOrderStatusEnum.CONFIRM.getCode()), "订单必须为待支付状态");
        Assert.isTrue(rideOrder.getCloseType().equals(CommonConstant.ONE), "当前结算类型不允许修改优惠券");

        BigDecimal orderMoney = rideOrder.getBeforeMoney();
        if (rideOrder.getBeforeMoney() == null || rideOrder.getBeforeMoney().compareTo(BigDecimal.ZERO) == 0) {
            orderMoney = rideOrder.getBeforeTimeMoney().add(rideOrder.getOverRideTimeMoney()).add(rideOrder.getBeforeDistanceMoney()).add(rideOrder.getOverDistanceMoney());
        }
        Assert.isTrue(orderMoney.compareTo(BigDecimal.ZERO) > 0, "骑行费用为0，无需使用优惠券");
        // 有使用骑行卡
        if (rideOrder.getCardRecordId() != null) {
            if(rideOrder.getCardFreeMoney() != null && rideOrder.getCardFreeMoney().compareTo(BigDecimal.ZERO) > 0) {
                orderMoney = orderMoney.subtract(rideOrder.getCardFreeMoney());
                orderMoney = orderMoney.compareTo(BigDecimal.ZERO) < 0 ? new BigDecimal(0) : orderMoney;
            }else if(rideOrder.getCardFreeTime() != null && rideOrder.getCardFreeTime() >= rideOrder.getAllTime()) {
                orderMoney = BigDecimal.ZERO;
            }
            Assert.isTrue(orderMoney.compareTo(BigDecimal.ZERO) > 0, "骑行卡优惠后金额为0，无需使用优惠券");
        }
        // 赋值优惠券
        if (form.getCouponId() != null) {
            if (rideOrder.getCouponId() != null && rideOrder.getCouponId().equals(form.getCouponId())) {
                return AjaxResult.success("优惠券没有改变");
            }

            BikeAreaParam bikeParam = agentParamCacheService.getParam(LocalMapUtil.getAgentInfo().getId(), rideOrder.getAreaId());
            boolean allowCoupon = rideOrder.getDispatchMoney().compareTo(new BigDecimal(0)) > 0 ? bikeParam.getUserDispatchAllowDiscount() : true;
            Assert.isTrue(allowCoupon, "抱歉，系统已禁止罚款订单使用优惠券");
            MemberCouponVo memberCoupon = memberCouponService.getByCouponId(rideOrder.getAreaId(), rideOrder.getMemberId(), CouponInfoTypeEnum.RIDE.getCode(), orderMoney, form.getCouponId(), rideOrder.getOpenTime());

            LambdaUpdateWrapper<EbRideOrder> update = new LambdaUpdateWrapper<>();
            update.set(EbRideOrder::getCouponId, memberCoupon.getId());
            if (memberCoupon.getCouponType().equals(CouponTypeEnum.MONEY.getCode())) {
                update.set(EbRideOrder::getCouponMoney, memberCoupon.getCouponMoney());
                orderMoney = orderMoney.subtract(memberCoupon.getCouponMoney());
            } else if (memberCoupon.getCouponType().equals(CouponTypeEnum.RATE.getCode())) {
                BigDecimal rateMoney = orderMoney.multiply(memberCoupon.getCouponRate()).setScale(2, RoundingMode.HALF_UP);
                update.set(EbRideOrder::getCouponMoney, orderMoney.subtract(rateMoney));
                orderMoney = rateMoney;
            }
            orderMoney = orderMoney.compareTo(BigDecimal.ZERO) < 0 ? new BigDecimal(0) : orderMoney;

            rideOrderService.update(update.set(EbRideOrder::getOrderMoney, orderMoney)
                    .set(EbRideOrder::getMoney, orderMoney.add(rideOrder.getDispatchMoney()).add((rideOrder.getHelmetPay() != null? rideOrder.getHelmetPay() : BigDecimal.ZERO)))
                    .eq(EbRideOrder::getId, rideOrder.getId()));

            // 取消原本消耗的优惠券 消耗掉当前选择的优惠券
            memberCouponService.useCoupon(form.getCouponId());
            if(rideOrder.getCouponId() != null) {
                memberCouponService.cancelUseCoupon(rideOrder.getCouponId());
            }
        } else {
            // 原来也没有优惠券
            if (rideOrder.getCouponId() == null) {
                return AjaxResult.success("优惠券没有改变");
            }
            // 清空优惠券
            rideOrderService.update(new LambdaUpdateWrapper<EbRideOrder>()
                    .set(EbRideOrder::getCouponId, null)
                    .set(EbRideOrder::getCouponMoney, BigDecimal.ZERO)
                    .set(EbRideOrder::getOrderMoney, orderMoney)
                    .set(EbRideOrder::getMoney, orderMoney.add(rideOrder.getDispatchMoney()).add((rideOrder.getHelmetPay() != null? rideOrder.getHelmetPay() : BigDecimal.ZERO)))
                    .eq(EbRideOrder::getId, rideOrder.getId()));
            // 取消原本消耗的优惠券
            if(rideOrder.getCouponId() != null) {
                memberCouponService.cancelUseCoupon(rideOrder.getCouponId());
            }
        }
        return AjaxResult.success("修改成功");
    }

    @ApiOperation("判断订单是否正在支付")
    @GetMapping("/is/paying")
    public AjaxResult isPayIng(String orderNo) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        EbRideOrder rideOrder = rideOrderService.getByNo(orderNo, agentUser.getId());
        Assert.notNull(rideOrder, "不存在的订单号");
        if (rideOrder.getPayId() == null) {
            return AjaxResult.success("订单没有支付中");
        }
        if (rideOrder.getStatus().equals(RideOrderStatusEnum.COMPLETE.getCode())) {
            throw new BadResponseException(220, "订单支付完成");
        }
        EbPreOrder preOrder = preOrderService.getPayIng(rideOrder.getPayId());
        if (preOrder != null) {
            throw new BadResponseException(210, "订单支付中");
        }
        return AjaxResult.success("订单没有支付中");
    }

    @ApiOperation("支付订单")
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody RideOrderPayForm rideOrderPayForm) throws Exception {
        Assert.isTrue(StrUtil.isNotBlank(rideOrderPayForm.getOrderNo()), "缺少订单号");
        Assert.notNull(rideOrderPayForm.getPayChannel(), "请选择支付渠道");
        Assert.notNull(rideOrderPayForm.getChannelType(), "缺少渠道支付方式");
        AgentUser agentUser = AuthUtil.getAgentUser();
        EbRideOrder rideOrder = rideOrderService.getByNo(rideOrderPayForm.getOrderNo(), agentUser.getId());
        Assert.notNull(rideOrder, "不存在的订单号:" + rideOrderPayForm.getOrderNo());
        if (rideOrder.getStatus().equals(RideOrderStatusEnum.COMPLETE.getCode())) {
            throw new BadResponseException(220, "订单支付完成");
        } else if (rideOrder.getStatus().equals(RideOrderStatusEnum.RIDING.getCode()) || rideOrder.getStatus().equals(RideOrderStatusEnum.PAUSE.getCode())) {
            // 用户订单结算
            rideOrderService.orderSettleForClose(rideOrder, null, UserTypeEnum.MEMBER.getCode());
            rideOrder = rideOrderService.getById(rideOrder.getId());
            if (rideOrderService.autoPay(rideOrder, UserTypeEnum.MEMBER.getCode())) {
                return AjaxResult.success("支付成功");
            }
        } else if (rideOrder.getStatus().equals(RideOrderStatusEnum.CONFIRM.getCode())) {
            if (rideOrder.getPayId() != null) {
                EbPreOrder preOrder = preOrderService.getPayIng(rideOrder.getPayId());
                if (preOrder != null) {
                    throw new BadResponseException(210, "微信支付分订单扣款中，请稍候再试");
                }
            }

            // 用户正在单独支付罚款，转罚款支付逻辑
            if (rideOrder.getPenaltyPayStatus().equals(RideOrderPenaltyPayStatusEnum.WAIT_PAY_PENALTY.getCode())) {
                return ridePenaltyService.payByOrder(ServletUtil.getIp(), rideOrder, rideOrderPayForm);
            }
            // 取消支付分订单
            preOrderService.cancelOrderByRideOrder(rideOrder);
        }

        if (rideOrderPayForm.getPayChannel().equals(PayChannelEnum.WALLET.getCode())) {
            EbMemberWallet memberWallet = memberWalletService.getMemberWallet(agentUser.getId());
            // 用户总余额 充值金额 + 赠送余额
            BigDecimal memberMoney = memberWallet.getChargeMoney().add(memberWallet.getGiftMoney());
            if (memberMoney.compareTo(rideOrder.getMoney())  < 0) {
                return AjaxResult.error("钱包充值余额不足");
            }
        }

        EbMemberPay memberPay = memberPayService.createPay(rideOrder.getAreaId(), agentUser.getId(), MemberPayBusinessTypeEnum.RIDE_ORDER_PAY, rideOrder.getId(),
                rideOrder.getMoney(), rideOrderPayForm.getPayChannel());

        // 更新部分支付信息
        rideOrderService.update(new LambdaUpdateWrapper<EbRideOrder>()
                .set(EbRideOrder::getPayId, memberPay.getId())
                .set(EbRideOrder::getPayNo, memberPay.getPayNo())
                .set(rideOrder.getPenaltyPayStatus().equals(CommonConstant.TWO), EbRideOrder::getPenaltyPayStatus, CommonConstant.ONE)
                .eq(EbRideOrder::getId, rideOrder.getId()));

        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        EbMemberInfo memberInfo = memberInfoService.getById(agentUser.getId());

        // 拦截新版支付逻辑
        EbAgentInfo info = agentInfoService.getById(agentInfo.getId());
        EbPayAccount payAccount = payAccountService.getPayAccount(info.getPayAccountId(), memberInfo.getId());
        if (payAccount != null && (rideOrderPayForm.getPayChannel().equals(PayChannelEnum.WXPAY.getCode()) || rideOrderPayForm.getPayChannel().equals(PayChannelEnum.ALIPAY.getCode()))) {
            PayChannelEnum payChannel = PayChannelEnum.getByCode(rideOrderPayForm.getPayChannel());
            BikePayForm bikePayForm = new BikePayForm();
            bikePayForm.setMemberPayId(memberPay.getId());
            bikePayForm.setPayBusinessType(MemberPayBusinessTypeEnum.RIDE_ORDER_PAY);
            bikePayForm.setPayChannel(payChannel);
            bikePayForm.setMoney(rideOrder.getMoney());
            bikePayForm.setOpenId(StrUtil.isNotBlank(rideOrderPayForm.getOpenId()) ? rideOrderPayForm.getOpenId() : memberInfo.getOpenId());
            bikePayForm.setAlipayUserId(memberInfo.getAlipayUserId());
            bikePayForm.setAlipayOpenId(memberInfo.getAlipayOpenId());
            bikePayForm.setAreaId(rideOrder.getAreaId());
            bikePayForm.setMemberId(rideOrder.getMemberId());
            bikePayForm.setBusinessId(rideOrder.getId());
            bikePayForm.setClientIp(ServletUtil.getIp());
            // 骑行中支付限制订单过期时间
            if (rideOrder.getStatus().equals(RideOrderStatusEnum.RIDING.getCode()) || rideOrder.getStatus().equals(RideOrderStatusEnum.PAUSE.getCode())) {
                bikePayForm.setExpireMin(4);
            }
            return payClient.pay(agentInfo.getId(), bikePayForm);
        }

        String notifyUrl = "http://"+ agentInfo.getDomain() + "/api/v1/bikeuser/notify";
        AjaxResult result = null;
        if (rideOrderPayForm.getPayChannel().equals(PayChannelEnum.WXPAY.getCode())) {
            Assert.isTrue(StrUtil.isNotBlank(agentInfo.getWxMchId()), "未开启微信支付");
            if (rideOrderPayForm.getChannelType().equals(ChannelTypeEnum.MINI.getCode())) {
                String openId = StrUtil.isNotBlank(rideOrderPayForm.getOpenId()) ? rideOrderPayForm.getOpenId() : memberInfo.getOpenId();
                Assert.isTrue(StrUtil.isNotBlank(openId), "缺少openid");
                String timeExpire = null;
                // 骑行中支付，订单设置过期时间
                if (rideOrder.getStatus().equals(RideOrderStatusEnum.RIDING.getCode()) || rideOrder.getStatus().equals(RideOrderStatusEnum.PAUSE.getCode())) {
                    timeExpire = DateUtil.format(DateUtil.offsetMinute(new Date(), 4), "yyyy-MM-dd'T'HH:mm:ssXXX");
                }
                result  = AjaxResult.success(WxPayUtil.jsapiTransactions(
                        agentInfo.getWxMiniAppid(),
                        agentInfo.getWxMchId(),
                        openId,
                        "支付骑行订单",
                        memberPay.getPayNo(),
                        memberPay.getMoney(),
                        timeExpire,
                        agentInfo.getWxKeyPath(),
                        agentInfo.getWxCertPath(),
                        notifyUrl + "/wxpay/pay/" + LocalMapUtil.getAgentInfo().getAgentNo()
                ));

            }
        } else if (rideOrderPayForm.getPayChannel().equals(PayChannelEnum.ALIPAY.getCode())) {
            // 支付宝用户唯一标识user_id 和open_id必须有一个有值
            String timeExpire = "10m";
            // 骑行中支付，订单设置过期时间
            if (rideOrder.getStatus().equals(RideOrderStatusEnum.RIDING.getCode()) || rideOrder.getStatus().equals(RideOrderStatusEnum.PAUSE.getCode())) {
                timeExpire = "4m";
            }
            Assert.isTrue(StrUtil.isNotBlank(memberInfo.getAlipayUserId()) || StrUtil.isNotBlank(memberInfo.getAlipayOpenId()), "用户缺少支付宝用户标识");
            result = AjaxResult.success(AliPayUtil.getTradeCreateRequestParam(
                    agentInfo.getAliMiniAppid(),
                    memberInfo.getAlipayUserId(),
                    memberInfo.getAlipayOpenId(),
                    "支付骑行订单",
                    memberPay.getPayNo(),
                    memberPay.getMoney(),
                    timeExpire,
                    agentInfo.getAliPayPrivateKey(),
                    agentInfo.getAliPayCertPath(),
                    agentInfo.getAliPayPublicCertPath(),
                    agentInfo.getAliPayRootCertPath(),
                    notifyUrl + "/ali/pay/" + LocalMapUtil.getAgentInfo().getAgentNo()
            ));
        } else if (rideOrderPayForm.getPayChannel().equals(PayChannelEnum.WALLET.getCode())) {
            memberPayService.paySuccessByPay(memberPay, null);
            result = AjaxResult.success("支付成功");
        }
        if(result == null){
            return AjaxResult.error("不支持的支付方式！");
        }
        return result;
    }

    @ApiOperation("待支付订单选择骑行卡优惠信息")
    @PostMapping("/use/card")
    public AjaxResult<List<RideOrderUseCardFeeVo>> useCard(@RequestBody RideOrderUseCardForm form) {
        Assert.notNull(form.getOrderNo(), "缺少订单号");
        return AjaxResult.success(rideOrderService.rideUseCard(form.getOrderNo(), AuthUtil.getAgentUser().getId()));
    }

    @ApiOperation("获取订单临时停车次数")
    @GetMapping("/stop/times")
    public AjaxResult<RideOrderStopTimesVo> orderStopTimes(String orderNo) {
        Assert.isTrue(StrUtil.isNotBlank(orderNo), "缺少订单号");
        return AjaxResult.success(rideOrderService.orderStopTimes(orderNo, AuthUtil.getAgentUser().getId()));
    }
}
